package cn.com.hatech.blog.module.admin.comment.service.impl;

import cn.com.hatech.blog.common.exception.TipException;
import cn.com.hatech.blog.module.admin.article.entity.Article;
import cn.com.hatech.blog.module.admin.article.mapper.ArticleMapper;
import cn.com.hatech.blog.module.admin.comment.entity.Comment;
import cn.com.hatech.blog.module.admin.comment.mapper.CommentMapper;
import cn.com.hatech.blog.module.admin.comment.service.ICommentService;
import cn.com.hatech.blog.module.admin.comment.vo.CommentVO;
import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @projectName: hatech-blog
 * @package: cn.com.hatech.blog.module.admin.service.impl
 * @className: CommentServiceImpl
 * @author: xuruikai
 * @description: 评论信息业务层接口实现
 * @date: 2020/1/11 14:27
 * @version: 1.0
 */
@Slf4j
@Service("commentService")
public class CommentServiceImpl implements ICommentService {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private ArticleMapper contentMapper;

    @Override
    public void insertComment(Comment comments) {
        if (null == comments) {
            throw new TipException("评论对象为空");
        }
        if (StringUtils.isEmpty(comments.getAuthor())) {
            comments.setAuthor("热心网友");
        }
        if (StringUtils.isNotEmpty(comments.getMail()) && !Validator.isEmail(comments.getMail())) {
            throw new TipException("请输入正确的邮箱格式");
        }
        if (StringUtils.isEmpty(comments.getContent())) {
            throw new TipException("评论内容不能为空");
        }
        if (!Validator.isBetween(comments.getContent().length(), 5, 2000)) {
            throw new TipException("评论字数在5-2000个字符");
        }
        if (null == comments.getArticleId()) {
            throw new TipException("评论文章不能为空");
        }
        Article content = contentMapper.selectById(comments.getArticleId());
        if (null == content) {
            throw new TipException("不存在的文章");
        }
        comments.setOwnerId(content.getAuthorId());
        comments.setCreateTime(new Date());
        if (StringUtils.isEmpty(comments.getParent())) {
            comments.setParent("0");
        }
        commentMapper.insert(comments);

    }

    @Override
    public Page<CommentVO> getComments(String cid, int page, int limit) {
        if (null != cid) {
            QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
            commentQueryWrapper.lambda().eq(Comment::getArticleId, cid).eq(Comment::getParent, 0).eq(Comment::getStatus, 1);
            commentQueryWrapper.orderByDesc("id");
            List<Comment> parents = commentMapper.selectList(commentQueryWrapper);

            Page<Comment> commentPaginator = new Page<>();
            commentPaginator.setRecords(parents);
            Page<CommentVO> returnBo = copyPage(commentPaginator);
            if (parents.size() != 0) {
                List<CommentVO> comments = new ArrayList<>(parents.size());
                parents.forEach(parent -> {
                    CommentVO comment = new CommentVO(parent);
                    comments.add(comment);
                });
                returnBo.setRecords(comments);
            }
            return returnBo;
        }
        return null;
    }

    @Override
    public IPage<Comment> selectPage(int page, int limit) {
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        commentQueryWrapper.orderByDesc("create_time");
        return commentMapper.selectPage(new Page<>(page, limit), commentQueryWrapper);
    }

    @Override
    public void update(Comment comments) {
        if (null != comments && null != comments.getId()) {
            commentMapper.updateById(comments);
            // 更新评论次数
            Article content = contentMapper.selectById(comments.getArticleId());
            Article temp = Article.builder().id(content.getId()).commentsNum(content.getCommentsNum() + 1).build();
            contentMapper.updateById(temp);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new TipException("评论信息主键为空");
        }
        Comment comment = this.commentMapper.selectById(id);
        if (null == comment) {
            throw new TipException("不存在该评论");
        }
        commentMapper.deleteById(id);
        Article content = contentMapper.selectById(comment.getArticleId());
        if (null != content && content.getCommentsNum() > 0) {
            Article temp = Article.builder().id(content.getId()).commentsNum(content.getCommentsNum() + 1).build();
            contentMapper.updateById(temp);
        }
    }

    /**
     * copy原有的分页信息，除数据
     *
     * @param ordinal
     * @param <T>
     * @return
     */
    private <T> Page<T> copyPage(Page ordinal) {
        return ordinal;
    }
}
